package com.yykj.weifenxiao.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yykj.drup.client.Store;
import com.yykj.weifenxiao.server.config.WiFenXiaoConfig;
import com.yykj.weifenxiao.server.mapper.StoreDao;
import com.yykj.weifenxiao.server.model.WIStore;
import com.yykj.weifenxiao.server.service.AccessTokenService;
import com.yykj.weifenxiao.server.service.WiFenXiaoStoreService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author zeng
 * @Date 2022/3/9
 */
@Service
@AllArgsConstructor
public class WiFenXiaoStoreServiceImpl extends ServiceImpl<StoreDao, Store> implements WiFenXiaoStoreService {

    final AccessTokenService accessTokenService;
    final StoreDao storeDao;

    @Transactional
    @Override
    public void insertOrUpdateStore(List<WIStore> wiStoreList) {

        wiStoreList.forEach(wiStore -> {
            Store store = new Store();
            BeanUtil.copyProperties(wiStore,store);
            store.setGrade(wiStore.getRank());
            QueryWrapper<Store>  wrapper = new QueryWrapper<Store>().eq("user_id", store.getUserId());
            Store selectOne = storeDao.selectOne(wrapper);
            if (selectOne == null){
                storeDao.insert(store);
            }else {
                storeDao.update(store,wrapper);
            }
        });
    }




    @Override
    public List<WIStore> storeList() {
        String accessToken = accessTokenService.getAccessToken();
        String requestUrl = "/store/list";
        Map<String,Object> map = new HashMap<>();
        map.put("access_token",accessToken);
        String body = HttpUtil.get(WiFenXiaoConfig.baseUrl + requestUrl, map);
        JSONObject jsonObject = JSONUtil.parseObj(body,true);
        Object storeList = jsonObject.get("storeList");
        JSONArray array = JSONUtil.parseArray(storeList,true);
        List<WIStore> wiStores = JSONUtil.toList(array, WIStore.class);
        return wiStores;

    }

    @Override
    public WIStore selectStoreByUserId(Integer userId) {
        String accessToken = accessTokenService.getAccessToken();
        String requestUrl = "/store/info";
        Map<String,Object> map = new HashMap<>();
        map.put("access_token",accessToken);
        map.put("user_id",userId);
        String body = HttpUtil.get(WiFenXiaoConfig.baseUrl + requestUrl, map);
        System.out.println(body);
        WIStore store = JSONUtil.toBean(JSONUtil.parseObj(body, false), WIStore.class);
        return store;
    }


}
